package com.zl.rbac.util;

import com.zl.rbac.entity.User;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Set;

/**
 * user的上下文
 *    对你登录的user相关操作
 *       1) 把登录的user对象保存到session
 *       2) 从session获取当前登录的user对象
 * @ClassName: UserContext
 * @author: suke
 * @since: 2020/12/24 16:48
 */
public class UserContext{
    public  static  final  String  USER_IN_SESSION = "currentLoginUser";
    public  static  final  String  PERMISSIONS_IN_SESSION = "permissionsInSession";
    /**
     * 
     * @Title: 把登录的user对象保存到Session域
     * @param  user   登录的user对象
     * @return void
     * @author: suke
     * @since: 2020/12/24 17:17
     */
    public static  void  setUserInSession(User user){
        // currentRequestAttributes() 得到RequestAttributes类的对象
       RequestContextHolder.currentRequestAttributes().setAttribute(USER_IN_SESSION,user,RequestAttributes.SCOPE_SESSION);
    }

    /**
     *
     * @Title: 把登录用户所有的权限表达式保存到Session域
     * @param  expressionSet   权限表达式集合
     * @return void
     * @author: suke
     * @since: 2020/12/24 17:17
     */
    public static  void  setExpressionInSession(Set<String> expressionSet){
        // currentRequestAttributes() 得到RequestAttributes类的对象
        RequestContextHolder.currentRequestAttributes().setAttribute(PERMISSIONS_IN_SESSION,expressionSet,RequestAttributes.SCOPE_SESSION);
    }

    /**
     *
     * @Title: 从session域获取登录的user对象
     * @return Set<String>
     * @author: suke
     * @since: 2020/12/24 17:20
     */
    public static  Set<String>  getExpressionInSession(){
        return ( Set<String> )RequestContextHolder.currentRequestAttributes().getAttribute(PERMISSIONS_IN_SESSION,RequestAttributes.SCOPE_SESSION);
    }

    /**
     *
     * @Title: 从session域获取当前登录用户的所有权限表达式
     * @return com.zl.student.entity.User
     * @author: suke
     * @since: 2020/12/24 17:20
     */
    public static  User  getCurrent(){
        return (User)RequestContextHolder.currentRequestAttributes().getAttribute(USER_IN_SESSION,RequestAttributes.SCOPE_SESSION);
    }
}
